package per.jdz.lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 线程就是一个单独的资源类，没有任何附属操作
 * 1. 属性、方法
 */

public class SaleTicketDemo02 {
    public static void main(String[] args) {
        // 并发：多线程操作同一个资源类把资源类丢入线程
        Ticket ticket = new Ticket();
        new Thread(()-> {
            for (int i = 1; i <= 10; i++) {
                ticket.sale(i);
            }
        }).start();
        new Thread(()-> {
            for (int i = 1; i <= 10; i++) {
                ticket.sale(i);
            }
        }).start();
        new Thread(()-> {
            for (int i = 1; i <= 10; i++) {
                ticket.sale(i);
            }
        }).start();

        System.out.println("主线程结束");
    }
}

// 资源类
class Ticket {
    // 属性、方法
    private int number = 103;
    Lock lock = new ReentrantLock();

    public void sale(int num) {
        lock.lock();
        try {
            if (num <= number) {
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                this.number -= num;
                System.out.println(Thread.currentThread().getName() + "卖出了" + num + "张票，剩余" + this.number + "张票");
            } else {
                System.out.println("票买完了，或者不够了" + this.number);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}